<template>
  <div class="tools-div">
    <el-button type="success" size="small" plain @click="importData">从Excel导入</el-button>
    <el-button type="primary" size="small" plain @click="exportData">导出Excel</el-button>
  </div>
  <el-tree :data="list" :props="defaultProps" :load="loadNode" lazy show-checkbox>
  </el-tree>

  <!-- Excel导入 -->
  <el-dialog v-model="dialogImportVisible" title="导入Excel" width="30%">
    <el-form label-width="120px">
      <el-form-item label="地区文件">
        <el-upload
          class="upload-demo"
          :action="`${BASE_URL}/admin/product/region/importData`"
          :on-success="onUploadExcelSuccess"
          :before-upload="beforeUploadExcel"
        >
          <el-button type="primary">上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 上传确认对话框 -->
  <el-dialog v-model="confirmUploadVisible" title="确认上传" width="30%">
    <div>你确定要上传这个文件吗？</div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="confirmUploadVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmUpload">确定</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { finAllList, exportExcelData, importExcelData } from "@/api/product/region";
import { finAllRegionList } from "@/pinia/modules/region";
import { BASE_URL } from "@/utils/request";
import { ElMessage } from "element-plus";

const regionStore = finAllRegionList();

const list = ref([]);
const defaultProps = {
  children: "children",
  label: "name"
};

// 加载子节点的方法
const loadNode = async (node, resolve) => {
  if (!node.data.loaded && !node.data.isLeaf) {
    node.data.loaded = true;
    const children = node.data.children || [];
    node.data.children = children;
  }
  resolve(node.data.children || []);
};

const fetchData = async () => {
  const { data: result } = await finAllList();
  regionStore.saveCategories(result);
  return result.children || [];
};

onMounted(async () => {
  const regions = regionStore.getCategories();
  if (regions != null && regions.length !== 0) {
    list.value = regions;
  } else {
    try {
      const data = await fetchData();
      list.value = data;
      location.reload();
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  }
});

const exportData = async () => {
  try {
    const res = await exportExcelData();
    const blob = new Blob([res], { type: "application/vnd.ms-excel" });
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = "地区数据.xlsx";
    link.click();
  } catch (error) {
    console.error("Error exporting data:", error);
  }
};

const dialogImportVisible = ref(false);
const confirmUploadVisible = ref(false);
let fileToUpload = null;

const importData = () => {
  dialogImportVisible.value = true;
};

const onUploadExcelSuccess = async (response, file) => {
  dialogImportVisible.value = false;
  await fetchData();
  ElMessage.success("操作成功");
};

const beforeUploadExcel = (rawFile) => {
  const suffix = rawFile.name.substring(rawFile.name.lastIndexOf(".") + 1).toLowerCase();
  const reg = /^(xlsx|xls)$/;
  if (!reg.test(suffix)) {
    ElMessage.warning("文件格式不支持！");
    return false;
  }
  fileToUpload = rawFile;
  confirmUploadVisible.value = true;
  return false;
};

const confirmUpload = () => {
  const uploadComponent = document.querySelector(".upload-demo input[type=file]");
  if (uploadComponent) {
    const dataTransfer = new DataTransfer();
    dataTransfer.items.add(fileToUpload);
    uploadComponent.files = dataTransfer.files;
    uploadComponent.dispatchEvent(new Event("change"));
  }
  confirmUploadVisible.value = false;
};
</script>

<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
